package com.lyc.service.impl;

import com.lyc.constant.Constant;
import com.lyc.dao.AddressMapper;
import com.lyc.entity.Address;
import com.lyc.entity.vo.AddressVo;
import com.lyc.service.IAddressService;
import com.lyc.utils.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements IAddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<AddressVo> getMyAddress(int uid) {
        List<AddressVo> result = null;
        List<Address> addressList = addressMapper.selectAllByUid(uid);
        if (CollectionUtil.notEmpty(addressList)) {
            result = new ArrayList<>();
            for (Address address : addressList) {
                AddressVo addressVo = new AddressVo();
                addressVo.setAddr(address);
                result.add(addressVo);
            }
        }
        return result;
    }

    //TODO 只能查询一条记录，如果将AddressVo对象中改成集合则会冲突
//    @Override
//    public List<AddressVo> getMyAddress(int uid) {
//        return addressMapper.selectAllByUid2(uid);
//    }

    @Override
    public void addOrUpdate(Address address) {
        if (address != null && address.getAid() != null)
            if (address.getAid() == 0)
                addressMapper.insertSelective(address);
            else
                addressMapper.updateByPrimaryKeySelective(address);
    }

    @Override
    public void setDefaultAddress(int uid, int aid) {
        //将当前用户的所有地址都设置为非默认地址类型
        List<Address> addressList = addressMapper.selectAllByUid(uid);
        for (Address address : addressList) {
            address.setType(Constant.NOT_DEFAULT_ADDRESS_TYPE);
            addressMapper.updateByPrimaryKeySelective(address);
        }
        //设置指定aid的地址为默认地址类型
        Address address = new Address();
        address.setAid(aid);
        address.setType(Constant.DEFAULT_ADDRESS_TYPE);
        addressMapper.updateByPrimaryKeySelective(address);
    }

    @Override
    public void deleteAddress(int aid) {
        addressMapper.deleteByPrimaryKey(aid);
    }

    @Override
    public Address getAddressByAid(int aid) {
        return addressMapper.selectByPrimaryKey(aid);
    }
}
